<template>
	<view class="content">


		<view class="map">
			<baidu-map class="bm-view" :center="center" :zoom="zoom" @ready="handler">
				<div v-for="(marker,index) of markers" :key="index">
					<bm-marker class="bmMarker" :dragging="true" @click="infoWindowOpen(marker)"
						:position="{lng: marker.lng, lat: marker.lat}"
						:icon="{url:index == 0 ? mapIcon1 : mapIcon,size: {width: 28, height: 28}}">
						<!-- 弹窗 -->
						<bm-info-window title="网点信息" :position="{lng: marker.lng, lat: marker.lat}"
							:show="marker.showFlag" @close="infoWindowClose(marker)" @open="infoWindowOpen(marker)">

							<div>{{marker.siteName}}</div>
							<div>距离{{marker.distance}}{{marker.unit}}</div>
							<!-- <div>经度:{{marker.lng}}</div>
							<div>纬度:{{marker.lat}}</div> -->
							<!-- <div class="btn" @click="navigation(marker)">导航</div> -->
						</bm-info-window>
					</bm-marker>
				</div>
				<!-- 点击导航 实现路线图 -->
				<bm-driving v-if="navFlag" :start="nav.start" :end="nav.end" @searchcomplete="handleSearchComplete"
					:panel="false" :autoViewport="true"></bm-driving>
			</baidu-map>
			<!-- <baidu-map class="map" :center="{lng: 116.404, lat: 39.915}" :zoom="15">
				<bm-marker :position="{lng: 116.404, lat: 39.915}" :dragging="true" @click="infoWindowOpen">
					<bm-info-window :show="show1" @close="infoWindowClose"
						@open="infoWindowOpen">我爱北京天安门</bm-info-window>
				</bm-marker>
			</baidu-map>
 -->
			<!-- <map id="map" style="width: 100%;height: 480rpx;" :longitude="longitude" :latitude="latitude" scale="16" :markers="markers" bindmarkertap="markerTap"></map> -->
			<!-- <bm-label @tap="infoWindowOpen(marker)" :content="marker.siteName == undefined ? '' : marker.siteName"
							:labelStyle="{ fontSize : '12px',background:'rgba(0, 0, 0, 0)',borderColor:'rgba(0, 0, 0, 0)',paddingLeft:'12px',fontWeight:'bolder'}"
							:offset="{width: 4,height:2 }" /> -->
		</view>

		<view class="box">
			<view class="netlist" v-for="(item,index) in networkList" :key="index"
				@click="changeSite(item,item.lat,item.lng)">
				<view class="">
					<view class="flx">
						<view class="left">
							<view class="image">

							</view>
							<!-- <image :src="item.img1" mode=""></image> -->
						</view>
						<view class="right">
							<view class="title">{{item.siteName}}</view>
							<view class="openTime">
								<text>正常运营</text> 开放时间: 周一至周日 8:00-17:00
							</view>
						</view>
					</view>
					<view class="line"></view>
					<view class="flx">
						<view class="addressSmall">
							<!-- <image src="../../static/images/addressSmall.png" mode=""></image> -->
							<view class="image">

							</view>
						</view>
						<view class="address">{{item.siteAddress}}</view>
					</view>

					<view class="flx2">
						<view class="distance">距您{{item.distance}}{{item.unit}}</view>
						<view class="tel" @click="makeCall(item.mobile)">服务电话: {{item.mobile}}</view>
					</view>
				</view>

			</view>
			<u-loadmore :status="status" :iconSize="17" v-if="networkList.length" />
		</view>
	</view>
</template>

<script>
	import request from '../../utils/request.js'
	import '../../static/js/ihgAppJssdk.js'
	import vConsole from "../../static/js/vconsole.min"
	// import mapIconPath from "../../static/images/localtion.png"
	import mapIconPath from "../../static/images/localtion5.png"
	import mapIconPath1 from "../../static/images/local.png"
	export default {
		data() {
			return {
				// vConsole: new vConsole(),
				//需要加载的数据必须要触碰到每一页的底部才会加载数据
				show1: false,
				infoWindowShow: {}, // 用于保存每个标记点信息窗口显示状态的对象
				status: 'loadmore',
				suo: true,
				title: 'map',
				mapIcon: mapIconPath,
				mapIcon1: mapIconPath1,
				scale: 9,
				latitude: '',
				longitude: '',
				networkList: [
					// {
					// 	title: '湖北省红安县再生资源回收网点',
					// 	state: '正常运营',
					// 	openTime: '周一至周日 8:00-17:00',
					// 	address: '湖北省黄冈市红安县城关镇王贵轩村',
					// 	distance: '200m',
					// 	tel: '13907258082'
					// }
				],
				center: {
					lng: '',
					lat: ''
				},
				zoom: 13,
				markerPoint: {
					// lng: 116.404,
					// lat: 39.915
					lng: '',
					lat: ''
				},
				flag: false,
				lng: '',
				lat: '',
				page: 1,
				limit: 5,
				markers: [],
				itemList: [],
				navFlag: false,
				nav: {
					// start: '浙江省杭州市临平区迎宾路333-18',
					// end: '湖北省黄冈市团风县平麓山村村民委员会朝阳山村3组紫金种养合作社',
					start: '',
					end: ''
				},
				path: ''
			};
		},
		onShow() {
			setTimeout(() => {
				this.getNearbyBranchesData()
			}, 800)
		},
		methods: {
			//信息弹层 这两个方法一定要加
			infoWindowClose(marker) {
				this.$set(marker, 'showFlag', false);
				this.nav.end = ''
			},
			infoWindowOpen(marker) {
				let that = this
				// 点击定位图标没有反应可能是因为在 Vue 中对象属性的动态添加和响应性问题导致的,在vue中动态添加一个对象属性,如果该属性不是响应式的，无法追踪到属性的变化，无法触发视图的更新，可以使用 Vue 提供的 $set 方法或者 Vue.set 方法来添加响应式属性，以便 Vue 监听到该属性的变化
				this.$set(marker, 'showFlag', true);
			},
			// 导航
			navigation(marker) {
				let that = this
				// that.nav.end = marker.siteAddress
				// 在显示新路径之前，先隐藏上一个路径
				that.navFlag = false;
				var point = new BMap.Point(marker.lng, marker.lat);
				var gc = new BMap.Geocoder();
				gc.getLocation(point, function(rs) {
					rs = JSON.parse(JSON.stringify(rs))
					that.nav.end = rs.address
					that.navFlag = true
				});
			},
			// 路线图
			handleSearchComplete(res) {
				if (res) {
					this.path = res.getPlan(0).getRoute(0).getPath()
				}

			},
			makeCall(phone) {
				let that = this
				this.itemList[0] = phone
				uni.showActionSheet({
					itemList: this.itemList, //itemList字段不变
					success: function(res) {
						if (!res.cancel && res.tapIndex !== undefined) {
							let tapData = this.itemList[res.tapIndex]
							uni.showModal({
								content: `拨打人号码：${phone}`,
								success: function(res) {
									uni.makePhoneCall({
										phoneNumber: tapData,
										success: function() {

										},
										fail: function() {

										}
									});
								}
							})

						}
					}.bind(this) // 绑定this作用域
				});
			},
			// 渲染地图和点位
			handler({
				BMap,
				map
			}) {
				let that = this
				var latitude;
				var longitude;
				ihgAppJssdk.map.getLocation({
					success: function(res) {
						latitude = JSON.parse(res).latitude
						longitude = JSON.parse(res).longitude
						that.center.lng = longitude
						that.center.lat = latitude
						that.markerPoint.lng = longitude
						that.markerPoint.lat = latitude
						// that.center.lng = 114.624593
						// that.center.lat = 31.294312
						// that.markerPoint.lng = 114.624593
						// that.markerPoint.lat = 31.294312
						// that.zoom = 13
						that.zoom = 13
					}
				})

				// if(latitude && longitude){
				// 	uni.getLocation({
				// 		type: 'gcj02',
				// 		geocode: true,
				// 		geocodeAccuracy: 'highAccuracy', // 设置高精度模式
				// 		isHighAccuracy: true,
				// 		success: function(res) {
				// 			if (res) {
				// 				console.log(res,'55555555555555555')
				// 				// that.center.lng = res.longitude
				// 				// that.center.lat = res.latitude
				// 				that.center.lng = longitude
				// 				that.center.lat = latitude
				// 				// that.markerPoint.lng = res.longitude
				// 				// that.markerPoint.lat = res.latitude
				// 				that.markerPoint.lng = longitude
				// 				that.markerPoint.lat = latitude
				// 				console.log(that.markerPoint,'that.markerPoint')
				// 				// that.zoom = 13
				// 				that.zoom = 13
				// 			}
				// 		}
				// 	});
				// }

			},
			getNearbyBranchesData() {
				let that = this
				var lats;
				var lngs;
				ihgAppJssdk.map.getLocation({
					success: function(res) {

						lats = JSON.parse(res).latitude
						lngs = JSON.parse(res).longitude
						console.log(lats,lngs,'11111111')
						// console.log(latitude, longitude, 'latitude')
						// let x = lngs
						// let y = lats
						// let x_pi = (3.14159265358979324 * 10.0) / 1.0
						// let z = Math.sqrt(x * x + y * y) + 0.000001 * Math.sin(y * x_pi)
						// let theta = Math.atan2(y, x) + 0.0000299 * Math.cos(x * x_pi)
						//  lngs = z * Math.cos(theta) + 0.0078
						//  lats = z * Math.sin(theta) + 0.00003
						// var mar = {
						// 	lng: lngs,
						// 	lat: lats,
						// }
						var mar = {
							lng: lngs,
							lat: lats,
						}
						// var mar = {
						// 	lng: lngs,
						// 	lat: lats,
						// }
						// var mar = {
						// 	lng: longitude,
						// 	lat: latitude,
						// }
						var point = new BMap.Point(lngs, lats);
						var gc = new BMap.Geocoder();
						gc.getLocation(point, function(rs) {
							rs = JSON.parse(JSON.stringify(rs))
							that.nav.start = rs.address
						});
						that.latitude = res.latitude
						that.longitude = res.longitude
						request.get('/api/recycle/site/page', {
							page: that.page,
							limit: that.limit,
							// lng: res.longitude,
							// lat: res.latitude,
							lng: lngs,
							lat: lats,
							// lng: 114.624593,
							// lat: 31.294312,
						}).then(res => {
							if (res.code == 0) {
								// 使用深拷贝方式创建独立的数据副本,保证res.data.list不受影响,深拷贝 
								that.markers = JSON.parse(JSON.stringify(res.data.list));
								that.markers.unshift(mar)
								const newData = that.markers.map(item => {

									return {
										...item,
										showFlag: false
									};

									return item;
								});
								that.networkList = res.data.list
								if (res.data.list.length == '') {
									that.status = 'nomore';
									that.suo = false
								} else if (res.data.list.length < 5) {
									that.status = 'nomore';
									that.suo = false
								} else if (res.data.list.length = 5) {
									that.status = 'loadmore';
									that.suo = true
								}
							} else if (res.code == 5) {
								let that = this
								// that.getNearbyBranchesData()

							} else {
								uni.showToast({
									title: res.message,
									icon: 'none',
									duration: 2000
								})
							}

						})
					}
				})

				// if(this.lat&&this.lng){
				// let that = this
				// uni.getLocation({
				// 	type: 'gcj02',
				// 	geocode: true,
				// 	geocodeAccuracy: 'highAccuracy', // 设置高精度模式
				// 	isHighAccuracy: true,
				// 	success: function(res) {
				// 		if (res) {
				// 			//加偏移
				// 			let x = res.longitude
				// 			let y = res.latitude
				// 			let x_pi = (3.14159265358979324 * 10.0) / 1.0
				// 			let z = Math.sqrt(x * x + y * y) + 0.000001 * Math.sin(y * x_pi)
				// 			let theta = Math.atan2(y, x) + 0.0000299 * Math.cos(x * x_pi)
				// 			let lngs = z * Math.cos(theta) + 0.0078
				// 			let lats = z * Math.sin(theta) + 0.00003
				// 			var mar = {
				// 				lng: lngs,
				// 				lat: lats,
				// 			}
				// 			// var mar = {
				// 			// 	lng: longitude,
				// 			// 	lat: latitude,
				// 			// }
				// 			var point = new BMap.Point(lngs, lats);
				// 			var gc = new BMap.Geocoder();
				// 			gc.getLocation(point, function(rs) {
				// 				rs = JSON.parse(JSON.stringify(rs))
				// 				that.nav.start = rs.address
				// 			});
				// 			console.log(lngs, lats)
				// 			that.latitude = res.latitude
				// 			that.longitude = res.longitude
				// 			request.get('/api/recycle/site/page', {
				// 				page: that.page,
				// 				limit: that.limit,
				// 				// lng: res.longitude,
				// 				// lat: res.latitude,
				// 				lng: lngs,
				// 				lat: lats,
				// 			}).then(res => {
				// 				if (res.code == 0) {
				// 					// 使用深拷贝方式创建独立的数据副本,保证res.data.list不受影响,深拷贝 
				// 					that.markers = JSON.parse(JSON.stringify(res.data.list));
				// 					that.markers.unshift(mar)
				// 					const newData = that.markers.map(item => {

				// 						return {
				// 							...item,
				// 							showFlag: false
				// 						};

				// 						return item;
				// 					});
				// 					that.networkList = res.data.list
				// 					if (res.data.list.length == '') {
				// 						that.status = 'nomore';
				// 						that.suo = false
				// 					} else if (res.data.list.length < 5) {
				// 						that.status = 'nomore';
				// 						that.suo = false
				// 					} else if (res.data.list.length = 5) {
				// 						that.status = 'loadmore';
				// 						that.suo = true
				// 					}
				// 				} else if (res.code == 5) {
				// 					let that = this
				// 					// that.getNearbyBranchesData()

				// 				} else {
				// 					uni.showToast({
				// 						title: res.message,
				// 						icon: 'none',
				// 						duration: 2000
				// 					})
				// 				}

				// 			})

				// 		}


				// 	}
				// });
			},

			onReachBottomGetNearbyBranchesData() {
				let that = this
				// uni.getLocation({
				// 	type: 'gcj02',

				// 	success: function(res) {
				// 		if (res) {
				// 			that.latitude = res.latitude
				// 			that.longitude = res.longitude
				// 			request.get('/api/recycle/site/page', {
				// 				page: that.page,
				// 				limit: that.limit,
				// 				// lng: res.longitude,
				// 				// lat: res.latitude,
				// 				lng: 114.624593,
				// 				lat: 31.294312,
				// 			}).then(res => {
				// 				if (res.code == 0) {
				// 					that.markers = that.markers.concat(res.data.list)
				// 					that.networkList = that.networkList.concat(res.data.list)
				// 					if (res.data.list.length == '') {
				// 						that.status = 'nomore';
				// 						that.suo = false
				// 					} else if (res.data.list.length < 5) {
				// 						that.status = 'nomore';
				// 						that.suo = false
				// 					} else if (res.data.list.length = 5) {
				// 						that.status = 'loadmore';
				// 						that.suo = true

				// 					}
				// 				} else {
				// 					uni.showToast({
				// 						title: res.data.message,
				// 						icon: 'none',
				// 						duration: 2000
				// 					})
				// 				}

				// 			})

				// 		}
				// 	}
				// });
				var lats;
				var lngs;
				ihgAppJssdk.map.getLocation({
					success: function(res) {

						lats = JSON.parse(res).latitude
						lngs = JSON.parse(res).longitude
						console.log(lats,lngs,'3333333333333333')
						var point = new BMap.Point(lngs, lats);
						var gc = new BMap.Geocoder();
						gc.getLocation(point, function(rs) {
							rs = JSON.parse(JSON.stringify(rs))
							that.nav.start = rs.address
						});
						that.latitude = res.latitude
						that.longitude = res.longitude
						request.get('/api/recycle/site/page', {
							page: that.page,
							limit: that.limit,
							// lng: res.longitude,
							// lat: res.latitude,
							lng: lngs,
							lat: lats,
							// lng: 114.624593,
							// lat: 31.294312,
						}).then(res => {
							if (res.code == 0) {
								that.markers = that.markers.concat(res.data.list)
								that.networkList = that.networkList.concat(res.data.list)
								if (res.data.list.length == '') {
									that.status = 'nomore';
									that.suo = false
								} else if (res.data.list.length < 5) {
									that.status = 'nomore';
									that.suo = false
								} else if (res.data.list.length = 5) {
									that.status = 'loadmore';
									that.suo = true

								}
							} else {
								uni.showToast({
									title: res.data.message,
									icon: 'none',
									duration: 2000
								})
							}


						})
					}
				})
			},
			getLocation() {
				// 获取当前位置信息
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						this.longitude = res.longitude;
						this.latitude = res.latitude;
						this.addMarker(this.longitude, this.latitude, '../../static/images/addressSmall.png');
					},
					fail: () => {

					}
				});
			},
			addMarker(longitude, latitude, iconPath) {
				// 添加标记点
				const marker = {
					iconPath: '../../static/images/addressSmall.png',
					id: new Date().getTime(),
					latitude: latitude,
					longitude: longitude,
					width: 30,
					height: 30
				};
				this.markers.push(marker);
			},
			markerTap(e) {

			},
			changeSite(marker, lat, lng) {
				let that = this
				this.center.lng = lng
				this.center.lat = lat

				this.nav.end = marker.siteAddress
				// 在显示新路径之前，先隐藏上一个路径
				this.navFlag = false;
				var point = new BMap.Point(marker.lng, marker.lat);
				var gc = new BMap.Geocoder();
				gc.getLocation(point, function(rs) {
					// that.nav.end = rs.surroundingPois[0].title
					// that.nav.end = marker.siteAddress
					that.navFlag = true
					if (rs.surroundingPois && rs.surroundingPois.length > 0) {
						// let selectedAddress = rs.surroundingPois[0].address;
						let selectedAddress = rs.surroundingPois[0].address + rs.surroundingPois[0].title || marker
							.siteAddress;
						that.nav.end = selectedAddress;
						that.navFlag = true;
						// let addressCounter = 0;

						// function selectNextAddress() {
						// 	if (addressCounter < rs.surroundingPois.length) {
						// 		let selectedAddress = rs.surroundingPois[addressCounter].address + rs
						// 			.surroundingPois[addressCounter].title;
						// 		that.nav.end = selectedAddress;
						// 		that.navFlag = true;
						// 		console.log(that.nav.end, '11111111222333');
						// 		addressCounter++;
						// 	} else {
						// 		addressCounter = 0; // 重置计数器
						// 	}
						// }

						// // 调用selectNextAddress函数以自动选择下一个地址
						// selectNextAddress();
					} else {
						rs = JSON.parse(JSON.stringify(rs))
						that.nav.end = rs.address
						that.navFlag = true
					}


				});
			},
			// 定义一个方法用于直接选择地址
			selectAddress(address) {
				// 这里可以添加逻辑处理选中该地址，例如将其设置为终点地址
				let selectedAddress = address.address + address.title;
				// 设置地址为终点
				this.nav.end = selectedAddress;
			}
		},
		onReachBottom() {
			if (this.suo) { //定义个小锁，当没有数据时锁住suo
				this.status = 'loading';
				this.page = ++this.page;

				setTimeout(() => {
					this.onReachBottomGetNearbyBranchesData()
				}, 1000)
				return;
			}
		},
	}
</script>

<style lang="less" scoped>
	.map {
		width: 100%;
		height: 480rpx;
		position: fixed;
		top: 0;
        z-index: 999999999;
		.bm-view {
			width: 750rpx;
			height: 480rpx;
		}
	}
	
	.box {
		padding-top: 480rpx;
	}

	.mapList {
		margin: 24rpx 0;
	}

	.netlist {
		width: 654rpx;
		background: #FFFFFF;
		margin: 24rpx;
		padding: 24rpx;

		.flx {
			display: flex;
			align-items: center;

			.left {
				.image {
					width: 82rpx;
					height: 82rpx;
					background: url('../../static/images/address.png');
					// vertical-align: middle;
					background-size: 100% 100%;
				}
			}

			.right {
				margin-left: 30rpx;

				.title {
					font-family: Source Han Sans SC;
					font-weight: 500;
					font-size: 36rpx;
					color: #000000;
					opacity: 0.85;
				}

				.openTime {
					font-family: Source Han Sans SC;
					font-weight: 500;
					font-size: 24rpx;
					color: #000000;
					margin-top: 6rpx;

					text {
						color: var(--global-bg-color);
						margin-right: 20rpx;
					}
				}
			}

			.addressSmall {

				// 改为背景图片,分页加载时图片权重过高,在百度地图上漂浮
				.image {
					width: 28rpx;
					height: 30rpx;
					background: url('../../static/images/addressSmall.png');
					background-size: 100% 100%;
				}
			}

			.address {
				font-family: Source Han Sans SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #000000;
				line-height: 36rpx;
				margin-left: 16rpx;
			}
		}

		.line {
			width: 100%;
			height: 1rpx;
			background: #EBEBEB;
			margin: 16rpx auto;
		}

		.flx2 {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-family: Source Han Sans SC;
			font-weight: 500;
			font-size: 24rpx;
			// color: rgba(153,163,183);
			color: #000000;
			line-height: 36rpx;
			margin-top: 10rpx;
			opacity: 0.45;
		}
	}

	.vehicleMap {
		width: 750rpx;
		height: 600rpx;
	}

	.content {
		background: #F1F4F9;
		padding-bottom: 2rpx;
	}

	.bmMarker {
		z-index: 9999999999999999999999;
	}

	.btn {
		color: white;
		background-color: #61B3F7;
		width: 100rpx;
		text-align: center;
	}
</style>